/*
 * @Author: Wangtao
 * @Date: 2021-01-14 15:34:22
 * @LastEditors: Wangtao
 * @LastEditTime: 2021-01-20 10:59:12
 */

interface Options {
  type: string
}

export default class PlayVoice {
  private el: HTMLAudioElement | undefined
  private options = {
    type: 'ringing'
  }

  constructor (options?) {
    if (options) {
      this.options = options
    }
    this.init()
  }

  private init () {
    this.el = this.createElement()
  }

  private createElement () {
    const elId = 'playVoice'
    const el = document.getElementById(elId)
    if (!(el instanceof HTMLAudioElement)) { // 没有音频dom,重新创建一个
      // throw new Error(`Element '${id}' not found or not an audio element.`)
      const audio = new Audio()
      audio.controls = true
      audio.autoplay = false
      audio.id = elId
      audio.style.display = 'none'
      audio.src = '/audio/ringing.wav'
      document.body.appendChild(audio)
      return document.getElementById(elId) as HTMLAudioElement
    } else {
      return el
    }
  }

  public play () {
    (this.el as HTMLAudioElement).currentTime = 0;
    (this.el as HTMLAudioElement).play()
  }

  public pause () {
    (this.el as HTMLAudioElement).pause()
  }
}
